package com.team7.happycommunity.businessservice.service.impl;

import com.team7.happycommunity.businessservice.entity.BusinessInfo;
import com.team7.happycommunity.businessservice.dao.BusinessInfoDao;
import com.team7.happycommunity.businessservice.entity.MyCenter;
import com.team7.happycommunity.businessservice.exception.LoginException;
import com.team7.happycommunity.businessservice.exception.MailboxStatusException;
import com.team7.happycommunity.businessservice.exception.RegisterException;
import com.team7.happycommunity.businessservice.service.BusinessInfoService;
import com.team7.happycommunity.businessservice.util.MailUtils;
import com.team7.happycommunity.businessservice.util.Md5Util;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (BusinessInfo)表服务实现类
 *
 * @author makejava
 * @since 2020-03-25 20:07:27
 */
@Service("businessInfoService")
public class BusinessInfoServiceImpl implements BusinessInfoService {
    @Resource
    private BusinessInfoDao businessInfoDao;

    @Value("${website}")
    private String website;
    @Value("${port}")
    private String port;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private HttpServletResponse response;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BusinessInfo queryById(Integer id) {
        return this.businessInfoDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<BusinessInfo> queryAllByLimit(int offset, int limit) {
        return this.businessInfoDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param businessInfo 实例对象
     * @return 实例对象
     */
    @Override
    public BusinessInfo insert(BusinessInfo businessInfo) throws Exception {
        //密码加密
        if(businessInfo.getPassword()!=null&&businessInfo.getPassword()!="")
        businessInfo.setPassword(Md5Util.encodeByMd5(businessInfo.getPassword()));
        int insert = this.businessInfoDao.insert(businessInfo);
        businessInfo.setId(insert);
        return businessInfo;
    }

    /**
     * 修改数据
     *
     * @param businessInfo 实例对象
     * @return 实例对象
     */
    @Override
    public BusinessInfo update(BusinessInfo businessInfo) {
        this.businessInfoDao.update(businessInfo);
        return this.queryById(businessInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.businessInfoDao.deleteById(id) > 0;
    }

    @Override
    public void login(String text, String password) throws Exception {
        BusinessInfo user =null;
        if(text.contains("@")){
            //为邮箱
            user=businessInfoDao.queryByMailbox(text);
            if(user.getMailboxStatus()!=0){
                throw new LoginException("账号不存在");
            }


        }else{
            user=businessInfoDao.queryByPhoneNumer(text);
        }
        if(user == null){
            throw new LoginException("账号不存在");
        }

        String realPassword = Md5Util.encodeByMd5(password);
        if (!user.getPassword().equals(realPassword)){
            throw new LoginException("密码不存在");
        }
        //保存用户名到cookie和redis中，存活时间24小时，原理，客户端发送cookie过来，我取出来值name,看redis中是否有cookie的值，有则登录，
        //无，则提醒用户登录；
        // request.getSession();
        Cookie c=new Cookie("name"+user.getName(),user.getName());
        //cookie存活时间24小时
        c.setMaxAge(60*60*24);
        c.setPath("/"); //根据个人的不用，在不同功能的路径下创建
        response.addCookie(c);
        //存储到redis中，
        //2.将验证码保存到redis中
        redisTemplate.boundValueOps("name"+user.getName()).set(user.getName());
        redisTemplate.boundValueOps("name"+user.getName()).expire(24, TimeUnit.HOURS);//24小时过期
    }

    @Override
    public boolean queryMailbox(String mailbox) {
        BusinessInfo user = businessInfoDao.queryByMailbox(mailbox);
        if(user==null||user.getMailboxStatus()!=0){
            return true;
        }
        return false;
    }

    @Override
    public void register(BusinessInfo user) {
        // 发送邮件，存储邮箱，并将mailbox_status状态改为1，并随机生成一个code邮箱令牌，并存储到数据库,密码加密
        //1.生成一个UUID数字
        String code = UUID.randomUUID().toString().replace("_","");
        user.setCode(code);
        String content="<a href='http://"+website+":"+port+"/personUser/activate?code="+code+"'>点击激活</a>";
        MailUtils.sendMail(user.getMailbox(),content,"幸福小区邀请您注册，请点击链接");
        //2.进行密码加密
        try {
            String password = Md5Util.encodeByMd5(user.getPassword());
            user.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //邮箱状态
        user.setMailboxStatus(1);
        //存储
        businessInfoDao.insert(user);
    }

    @Override
    public void phoneRegister(String cellPhNumber,String resetCode ) {
        //判断手机号是否被注册
        if(resetCode==null||!resetCode.equals("1")){
            BusinessInfo user = businessInfoDao.queryByPhoneNumer(cellPhNumber);
            if(user!=null){
                throw new RegisterException("手机号已经被注册");
            }
        }
        //1.生成一个六位验证码
        Random random=new Random();
        int code = random.nextInt(999999);
        if(code<100000){
            code=code+100000;
        }
        //2.将验证码保存到redis中
        redisTemplate.boundValueOps("code_"+cellPhNumber).set(code+"");
        redisTemplate.boundValueOps("code_"+cellPhNumber).expire(5, TimeUnit.MINUTES);//5分钟过期
        //3.将验证码发送到mq
        Map<String,String> map=new HashMap<>();
        map.put("phone",cellPhNumber);
        map.put("code",code+"");
        rabbitTemplate.convertAndSend("phone_code_exchange","phone."+cellPhNumber, map);
    }
    @Override
    public void codeCheck(String code, String phone) {
        //1.校验
        String sysCode = (String)redisTemplate.boundValueOps("code_" + phone).get();
        if(sysCode==null){
            throw new RegisterException("验证码过期或未发送");
        }
        if(!sysCode.equals(code)){
            throw new RegisterException("验证码不正确");
        }
    }
    @Override
    public void updateMailboxStatus(String code) {
        BusinessInfo user=new BusinessInfo();
        user.setCode(code);
        List<BusinessInfo> personUsers = businessInfoDao.queryAll(user);
        if(personUsers==null||personUsers.size()==0){
            throw new MailboxStatusException("激活码不正确");
        }
        //1.修改邮箱状态
        businessInfoDao.updateMailboxStatusByCode(code,0);
    }

    @Override
    public void updatePasswordByCellPhNumber(String cellPhNumber, String password) throws Exception {
        businessInfoDao.updatePasswordByCellPhNumber(cellPhNumber,Md5Util.encodeByMd5(password));
    }
    @Override
    public MyCenter queruyPersonageInfo(Integer userId){
       return businessInfoDao.queruyPersonageInfo(userId);
    }

    @Override
    public MyCenter queruyPersonageInfo2(Integer userId){
        return businessInfoDao.queruyPersonageInfo2(userId);
    }

    @Override
    public MyCenter queruyOrderSum(int i){
        return businessInfoDao.queruyOrderSum(i);
    }

    @Override
    public  MyCenter bookOrederSum(Integer userId, Integer status){
        return businessInfoDao.bookOrederSum(userId,status);
    }

    @Override
    public void updateByCellPhNumber(BusinessInfo user){
        businessInfoDao.updateByCellPhNumber(user);
    }

    @Override
    public BusinessInfo queryByPhone(String phone){
       return businessInfoDao.queryByPhone(phone);
    }

    @Override
    public String queryIncome(Integer userId){
      return   businessInfoDao.queryIncome(userId);
    }

}